from rest_framework import serializers
from utils.helper.token_helper import TokenHelper
from apps.sdk.weixin_services import WeixinServices
from apps.user.models import User


class UserLoginSerializer(serializers.Serializer):

    code = serializers.CharField(write_only=True)

    @staticmethod
    def login(code: str) -> str:
        openid, session_code = WeixinServices.get_openid_session_with_code(code)
        user = WeixinServices.save_openid_session(openid, session_code)
        token_pair = TokenHelper.generate_jwt_token(user.id.hex, openid)
        return token_pair


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ('wei_chat_open_id', 'session_key')


class UserAvatarProfileSerializer(serializers.Serializer):

    avatar = serializers.ImageField(write_only=True)

    def create(self, validated_data):
        request = self.context.get('request')
        current_user = getattr(request, 'current_user', None)
        setattr(current_user, 'avatar_url', validated_data['avatar'])
        current_user.save()
        return validated_data
